// 成绩详情页交互功能
document.addEventListener('DOMContentLoaded', function() {
    // 初始化所有图表和交互功能
    initScoreRateChart();
    initScoreTrendChart();
    initProgressBarAnimation();
    initButtonInteractions();
    initScrollAnimations();
    initDeleteConfirmations(); // 新增：初始化删除确认功能

    console.log('成绩详情页交互功能已初始化');
});

// 1. 得分率环形图
function initScoreRateChart() {
    const ctx = document.getElementById('scoreRateChart');
    if (!ctx) return;

    const score = parseInt('{{ exam_record.score }}');
    const fullScore = parseInt('{{ full_score }}');
    const lossScore = fullScore - score;
    const scoreRate = parseFloat('{{ score_rate }}');
    const subjectColor = '{{ exam_record.subject.color }}' || '#4361ee';

    // 创建渐变颜色
    const gradient = ctx.getContext('2d').createLinearGradient(0, 0, 200, 200);
    gradient.addColorStop(0, subjectColor);
    gradient.addColorStop(1, lightenColor(subjectColor, 30));

    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: [`得分 (${score}分)`, `失分 (${lossScore}分)`],
            datasets: [{
                data: [score, lossScore],
                backgroundColor: [
                    gradient,
                    'rgba(233, 236, 239, 1)'
                ],
                borderColor: [
                    subjectColor,
                    'rgba(233, 236, 239, 1)'
                ],
                borderWidth: 3,
                cutout: '75%'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        padding: 25,
                        font: {
                            size: 13,
                            family: "'Inter', sans-serif",
                            weight: '600'
                        },
                        usePointStyle: true,
                        pointStyle: 'circle',
                        color: '#495057'
                    }
                },
                tooltip: {
                    padding: 15,
                    backgroundColor: 'rgba(0, 0, 0, 0.85)',
                    titleFont: {
                        size: 14,
                        family: "'Inter', sans-serif",
                        weight: '600'
                    },
                    bodyFont: {
                        size: 14,
                        family: "'Inter', sans-serif"
                    },
                    cornerRadius: 12,
                    boxPadding: 8,
                    callbacks: {
                        label: function(context) {
                            const label = context.label || '';
                            const value = context.parsed;
                            const percentage = ((value / fullScore) * 100).toFixed(1);
                            return `${label}: ${value}分 (${percentage}%)`;
                        }
                    }
                }
            },
            animation: {
                animateRotate: true,
                animateScale: true,
                duration: 1800,
                easing: 'easeOutQuart'
            },
            cutout: '70%'
        }
    });
}

// 2. 成绩趋势折线图
function initScoreTrendChart() {
    const ctx = document.getElementById('scoreTrendChart');
    if (!ctx) return;

    try {
        const examRecords = JSON.parse('{{ student_exam_records|safe }}'.replace(/&quot;/g, '"'));
        if (!examRecords || examRecords.length < 2) return;

        const labels = examRecords.map(record => {
            const date = new Date(record.exam_date);
            return `${date.getMonth() + 1}/${date.getDate()}`;
        });

        const scores = examRecords.map(record => record.score);
        const fullScores = examRecords.map(record => record.full_score);
        const subjectColor = '{{ exam_record.subject.color }}' || '#4361ee';

        // 创建渐变
        const gradient = ctx.getContext('2d').createLinearGradient(0, 0, 0, 180);
        gradient.addColorStop(0, hexToRgba(subjectColor, 0.4));
        gradient.addColorStop(0.7, hexToRgba(subjectColor, 0.1));
        gradient.addColorStop(1, hexToRgba(subjectColor, 0.05));

        new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: '你的成绩',
                        data: scores,
                        borderColor: subjectColor,
                        backgroundColor: gradient,
                        borderWidth: 4,
                        tension: 0.4,
                        fill: true,
                        pointBackgroundColor: subjectColor,
                        pointBorderColor: '#ffffff',
                        pointBorderWidth: 3,
                        pointRadius: 6,
                        pointHoverRadius: 9,
                        pointHoverBackgroundColor: subjectColor,
                        pointHoverBorderColor: '#ffffff',
                        pointHoverBorderWidth: 4
                    },
                    {
                        label: '满分',
                        data: fullScores,
                        borderColor: 'rgba(40, 167, 69, 0.7)',
                        borderWidth: 2,
                        borderDash: [6, 4],
                        tension: 0,
                        fill: false,
                        pointRadius: 0,
                        pointHoverRadius: 0
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        min: Math.max(0, Math.min(...scores) - 10),
                        max: Math.max(...fullScores) + 5,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.06)',
                            drawBorder: false
                        },
                        ticks: {
                            font: {
                                family: "'Inter', sans-serif",
                                size: 12,
                                weight: '600'
                            },
                            color: '#6c757d'
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        },
                        ticks: {
                            font: {
                                family: "'Inter', sans-serif",
                                size: 12,
                                weight: '600'
                            },
                            color: '#6c757d'
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                        padding: 15,
                        backgroundColor: 'rgba(0, 0, 0, 0.85)',
                        titleFont: {
                            family: "'Inter', sans-serif",
                            size: 13,
                            weight: '600'
                        },
                        bodyFont: {
                            family: "'Inter', sans-serif",
                            size: 13
                        },
                        cornerRadius: 12,
                        boxPadding: 8,
                        callbacks: {
                            label: function(context) {
                                let label = context.dataset.label || '';
                                if (label) {
                                    label += ': ';
                                }
                                label += context.parsed.y + '分';
                                return label;
                            }
                        }
                    }
                },
                interaction: {
                    intersect: false,
                    mode: 'index'
                },
                animation: {
                    duration: 1800,
                    easing: 'easeOutQuart'
                }
            }
        });
    } catch (error) {
        console.warn('成绩趋势图表初始化失败:', error);
    }
}

// 3. 进度条动画
function initProgressBarAnimation() {
    const progressBars = document.querySelectorAll('.progress-bar');
    const progressTexts = document.querySelectorAll('.progress-text');

    progressBars.forEach((bar, index) => {
        const targetWidth = bar.getAttribute('data-width');

        // 设置初始状态
        bar.style.width = '0%';
        if (progressTexts[index]) {
            progressTexts[index].style.opacity = '0';
        }

        // 延迟执行动画
        setTimeout(() => {
            bar.style.transition = 'width 1.8s cubic-bezier(0.34, 1.56, 0.64, 1)';
            bar.style.width = targetWidth + '%';

            // 动画完成后显示文本
            setTimeout(() => {
                if (progressTexts[index]) {
                    progressTexts[index].style.opacity = '1';
                    progressTexts[index].style.transition = 'opacity 0.3s ease';
                }
            }, 1800);

        }, 500);
    });
}

// 4. 删除确认功能 - 新增
function initDeleteConfirmations() {
    const deleteButtons = document.querySelectorAll('.delete-btn');

    deleteButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();

            const questionNumber = this.getAttribute('data-question');
            const points = this.getAttribute('data-points');
            const form = this.closest('form');

            // 使用浏览器原生确认对话框
            const isConfirmed = confirm(
                `确定要删除「${questionNumber}题 - ${points}」的失分明细吗？\n\n删除后数据不可恢复，请谨慎操作。`
            );

            if (isConfirmed) {
                form.submit();
            }
        });
    });
}

// 5. 按钮交互效果
function initButtonInteractions() {
    const actionButtons = document.querySelectorAll('.action-btn');

    actionButtons.forEach(btn => {
        // 点击效果
        btn.addEventListener('mousedown', function() {
            this.style.transform = 'translateY(0) scale(0.95)';
        });

        btn.addEventListener('mouseup', function() {
            this.style.transform = 'translateY(-3px) scale(1)';
        });

        btn.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0) scale(1)';
        });

        // 悬停效果
        btn.addEventListener('mouseenter', function() {
            this.style.boxShadow = '0 10px 25px rgba(0, 0, 0, 0.2)';
        });

        btn.addEventListener('mouseleave', function() {
            this.style.boxShadow = '';
        });
    });
}

// 6. 滚动动画
function initScrollAnimations() {
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };

    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
                entry.target.style.transition = 'opacity 0.8s ease, transform 0.8s ease';
            }
        });
    }, observerOptions);

    // 观察所有卡片元素
    const animatedElements = document.querySelectorAll('.card, .loss-stat-card, .table-responsive');
    animatedElements.forEach(el => {
        el.style.opacity = '0';
        el.style.transform = 'translateY(30px)';
        observer.observe(el);
    });
}

// 7. 工具函数：颜色处理
function lightenColor(color, percent) {
    const num = parseInt(color.replace('#', ''), 16);
    const amt = Math.round(2.55 * percent);
    const R = (num >> 16) + amt;
    const G = (num >> 8 & 0x00FF) + amt;
    const B = (num & 0x0000FF) + amt;

    return '#' + (
        0x1000000 +
        (R < 255 ? (R < 1 ? 0 : R) : 255) * 0x10000 +
        (G < 255 ? (G < 1 ? 0 : G) : 255) * 0x100 +
        (B < 255 ? (B < 1 ? 0 : B) : 255)
    ).toString(16).slice(1);
}

function hexToRgba(hex, alpha) {
    const r = parseInt(hex.slice(1, 3), 16);
    const g = parseInt(hex.slice(3, 5), 16);
    const b = parseInt(hex.slice(5, 7), 16);

    return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}

// 8. 页面性能优化 - 延迟加载非关键资源
function loadNonCriticalResources() {
    // 可以在这里延迟加载图片或其他非关键资源
    const lazyImages = document.querySelectorAll('img[data-src]');

    const imageObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                img.src = img.dataset.src;
                img.classList.remove('lazy');
                imageObserver.unobserve(img);
            }
        });
    });

    lazyImages.forEach(img => imageObserver.observe(img));
}

// 9. 错误处理
function handleChartErrors() {
    window.addEventListener('error', function(e) {
        if (e.target && (e.target.tagName === 'CANVAS' || e.target.classList.contains('chartjs-render-monitor'))) {
            console.warn('图表渲染错误:', e.error);
            // 可以在这里添加备用显示方案
        }
    });
}

// 初始化错误处理
handleChartErrors();

// 初始化非关键资源加载
if ('requestIdleCallback' in window) {
    window.requestIdleCallback(loadNonCriticalResources);
} else {
    setTimeout(loadNonCriticalResources, 1000);
}

// 10. 页面可见性变化处理
document.addEventListener('visibilitychange', function() {
    if (!document.hidden) {
        // 页面重新可见时，重新初始化图表
        setTimeout(() => {
            initScoreRateChart();
            initScoreTrendChart();
        }, 100);
    }
});

console.log('成绩详情页脚本加载完成');